<template>
  <div class="app-container">
    <div class="app__form__container">
      <el-form
        ref="formRef"
        style="max-width: 100%"
        :model="dynamicValidateForm"
        label-width="auto"
        class="demo-dynamic"
        :inline="true"
      >
        <!-- :prop="domain.key" -->
        <el-form-item
          v-for="(domain, domainIndex) in dynamicValidateForm.domains"
          :key="domain.key"
          :label="domain.label"
          :prop="'domains.' + domainIndex + '.value'"
          :rules="domain.rule[0]"
          :style="{
            width:
              domain.formType === 'craftState' || domain.formType === 'image'
                ? '100%'
                : 'auto',
          }"
        >
          <template v-if="domain.formType === 'read'">
            <template v-if="domain.key === 'order_state'">
              <div
                class="form__row__container"
                :class="{
                  success__text: Number(domain.value) === 3,
                  primary__text: Number(domain.value) === 2,
                  danger__text: Number(domain.value) === 1,
                }"
              >
                {{
                  orderStateList.find((elm) => elm.value === domain.value)
                    ?.label || ""
                }}
              </div>
            </template>
            <template v-else>
              <div class="form__row__container">
                {{ domain.value || "" }}
              </div>
            </template>
          </template>
          <template v-if="domain.formType === 'input'">
            <el-input
              v-model="domain.value"
              :placeholder="domain.placeholder"
              :disabled="domain.key === 'number'"
              class="form__row__container"
            ></el-input>
          </template>
          <template v-if="domain.formType === 'textarea'">
            <el-input
              v-model="domain.value"
              :autosize="{ minRows: 2, maxRows: 4 }"
              class="form__row__container"
              type="textarea"
              :placeholder="domain.placeholder"
            ></el-input>
          </template>
          <template v-if="domain.formType === 'radio'">
            <el-select
              v-model="domain.value"
              clearable
              :placeholder="domain.placeholder"
              class="form__row__container"
            >
              <el-option
                v-for="item in domain.option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template v-if="domain.formType === 'checkbox'">
            <el-select
              v-model="domain.value"
              clearable
              multiple
              :placeholder="domain.placeholder"
              class="form__row__container"
            >
              <el-option
                v-for="item in domain.option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template v-if="domain.formType === 'number'">
            <el-input-number
              class="form__row__container"
              :min="0"
              :placeholder="domain.placeholder"
              v-model="domain.value"
            />
          </template>
          <template v-if="domain.formType === 'amount'">
            <el-input-number
              class="form__row__container"
              :precision="2"
              :step="0.1"
              :min="0"
              :placeholder="domain.placeholder"
              v-model="domain.value"
            />
          </template>
          <template v-if="domain.formType === 'datetime'">
            <el-date-picker
              class="form__row__container"
              type="datetime"
              :placeholder="domain.placeholder"
              :shortcuts="shortcuts"
              v-model="domain.value"
            />
          </template>
          <template v-if="domain.formType === 'image'">
            <div class="form__row__2__container">
              <MultiUpload v-model="domain.value" />
            </div>
          </template>
          <template v-if="domain.formType === 'craftState'">
            <div class="form__row__2__container">
              <template v-if="!domain.value">
                <el-button
                  type="primary"
                  @click="showCraftStateDialog(domainIndex, null)"
                  >选择工艺</el-button
                >
              </template>
              <template v-else>
                <div class="ma-b-15">
                  <el-button
                    type="primary"
                    @click="showCraftStateDialog(domainIndex, domain.value)"
                    >重新选择</el-button
                  >
                </div>
                <div class="row_content-container">
                  <div
                    class="content_item-container"
                    v-for="(item, index) in domain.value"
                    :key="item.id"
                  >
                    <div
                      class="item_content"
                      :class="{
                        item_content__success: Number(item.isDone) === 1,
                      }"
                      @click="
                        showToggleCraftStateDialog(item, index, domain.value)
                      "
                    >
                      {{ item.content || "暂无步骤内容" }}
                    </div>
                    <div
                      class="step-text"
                      v-if="index < domain.value.length - 1"
                    >
                      <i-ep-right class="icon" />
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div class="app__bottom__container">
      <el-button type="primary" @click="submitForm(formRef, true)"
        >保存</el-button
      >
      <el-button type="success" @click="submitForm(formRef, false)"
        >保存 +</el-button
      >

      <el-button @click="resetForm(formRef)">重置</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
    <!-- 选择工艺弹窗 -->
    <SelectCraftStateDialog
      ref="selectCraftStateDialogRef"
      @success="craftStateSuccess"
    />
    <!-- 修改工艺步骤弹窗 -->
    <EditCraftStateDialog
      ref="editCraftStateDialogRef"
      @success="EditCraftStateSuccess"
    />
    <!-- 设置面板 -->
    <RightPanel v-if="showSettings">
      <settings />
    </RightPanel>
  </div>
</template>

<script lang="ts" setup name="AddOrder">
defineOptions({
  name: "AddOrder",
  inheritAttrs: false,
});
import { useRouter, useRoute } from "vue-router";
import type { FormInstance } from "element-plus";

import SelectCraftStateDialog from "./components/SelectCraftStateDialog.vue";
import EditCraftStateDialog from "./components/EditCraftStateDialog.vue";

import { useSettingsStore } from "@/store/modules/settings";
import {
  getOrderField,
  getMaterialList,
  addOrder,
  editOrder,
  getOrderInfo,
} from "@/api/order";
import { type OrderFieldItem } from "@/api/order/types";
import { getDefaultCraft } from "@/api/craft/index";
import { type CraftItem, CraftContent } from "@/api/craft/types";
import { getDaysDifference, formatTime } from "@/utils/index";

// 仓库定义
const settingsStore = useSettingsStore();
const showSettings = computed(() => settingsStore.showSettings);

// 路由定义
const router = useRouter();
const route = useRoute();
const orderId = ref<any>(0);

// 定义表单
const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{
  domains: OrderFieldItem[];
}>({
  domains: [],
});
const formTypeList = [
  "input",
  "radio",
  "checkbox",
  "number",
  "textarea",
  "datetime",
  "read",
  "image",
  "craftState",
  "amount",
];
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

// 工单材料详情
const materialList = ref<any[]>([]);

// 选择工艺组件变量
const selectCraftStateDialogRef = ref<typeof SelectCraftStateDialog | null>(
  null
);
// 定义当前打开的选择工艺下标
const activeCraftStateDomainIndex = ref<number>(-1);

// 定义编辑工艺组件变量
const editCraftStateDialogRef = ref<typeof EditCraftStateDialog | null>(null);
// 定义当前正在编辑的工艺变量
const activeCraftList = ref<CraftContent[]>([]);
// 工单状态列表
const orderStateList = [
  {
    label: "未生产",
    value: 1,
  },
  {
    label: "生产中",
    value: 2,
  },
  {
    label: "已完工",
    value: 3,
  },
];

// 页面初始化函数
const initPage = () => {
  if (route.query.orderId) {
    orderId.value = route.query.orderId;
  }
  if (Number(orderId.value) > 0) {
    // 获取工单详情
    getOrderInfoService();
    // 获取材料详情
    getMaterialListService();
  } else {
    // 获取自定义字段列表
    getOrderFieldService();
  }
};

onMounted(() => {
  // 初始化调用
  initPage();
});
// 表单提交
const submitForm = (
  formEl: FormInstance | undefined,
  isBack: boolean = false
) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");
      handleSubmitOrder(isBack);
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 获取自定义字段列表
const getOrderFieldService = async () => {
  let params = {
    page: 1,
    limit: 0,
  };
  let res = await getOrderField(params);
  if (res) {
    setDynamicValidateFormDomains(res.data.list, false);
    getDefaultCraftService();
  }
};

// 获取工单详情
const orderInfoDetail = ref<any>({});
const getOrderInfoService = async () => {
  let params = {
    id: orderId.value || "",
  };
  let res = await getOrderInfo(params);
  if (res) {
    console.log("获取工单详情成功了  ", res);
    orderInfoDetail.value = res.data.info;
    const extraList = res.data.info?.extra || null;
    if (extraList) {
      setDynamicValidateFormDomains(extraList, true);
      getDefaultCraftService();
    }
  }
};

// 设置工单列表
const setDynamicValidateFormDomains = (
  list: OrderFieldItem[] = [],
  isEdit: boolean = false
) => {
  if (!list || !list.length) {
    return;
  }
  list
    .sort((a, b) => {
      return a.sort - b.sort;
    })
    .forEach((elm: OrderFieldItem) => {
      if (elm.isFormShow && Number(elm.isFormShow)) {
        console.log(
          "自定义字段对象 ",
          elm.label,
          elm.formType,
          elm.value,
          typeof elm.value,
          elm.option
        );
        switch (isEdit) {
          case true:
            // 编辑
            switch (elm.formType) {
              case "image":
                elm.value = elm.value.split(",");
                break;
              // case "craftState":
              //   elm.value = {
              //     content: elm.value.map((cElm: CraftContent) => {
              //       return {
              //         ...cElm,
              //       };
              //     }),
              //   };
              //   break;
              case "number":
                elm.value = isNaN(Number(elm.value)) ? 0 : Number(elm.value);
                break;
              case "amount":
                elm.value = isNaN(Number(elm.value)) ? 0 : Number(elm.value);
                break;

              default:
                const regex = /null|undefined|'|"/g;
                elm.value =
                  typeof elm.value === "string"
                    ? elm.value.replace(regex, "")
                    : elm.value;
                break;
            }
            setOrderStatus();
            break;
          case false:
            // 新增
            switch (elm.formType) {
              case "checkbox":
                elm.value = [];
                break;
              case "number":
                elm.value = 0;
                break;
              case "amount":
                elm.value = 0;
                break;
              case "image":
                elm.value = [];
                break;
              default:
                elm.value = "";
                break;
            }

            break;
          default:
            break;
        }
        elm.placeholder =
          elm.rule && elm.rule[0] && elm.rule[0].message
            ? elm.rule[0].message
            : "";
        // console.log("自定义对象的规则  ", elm.rule);
        dynamicValidateForm.domains.push(elm);
      }
    });
};

// 获取工单材料详情
const getMaterialListService = async () => {
  let params = {
    page: 1,
    limit: 0,
    filter: JSON.stringify({
      orderId: 0, // 需要在编辑工单的时候设置
    }),
  };
  let res = await getMaterialList(params);
  if (res) {
    console.log("获取材料详情成功了  ", res);
    if (res.data?.list?.length) {
      materialList.value = res.data.list.filter((elm) => {
        return elm.iTEMCODE;
      });
    }
    // materialList.value = []

    // if (res.data.list && res.data.list.length) {
    //   res.data.list.forEach((elm) => {
    //     if (elm.iTEMCODE) {
    //       materialList.value.push(elm)
    //     }
    //   })
    // }
  }
};

// 获取默认报工数量
const defaultReportingNum = computed(() => {
  return materialList.value[0] ? materialList.value[0].pLANQTY : 0;
});

// 工艺逻辑
// 获取默认工艺
const getDefaultCraftService = async () => {
  let params = {};
  let res = await getDefaultCraft(params);
  if (res) {
    const findIndex = dynamicValidateForm.domains.findIndex(
      (elm) => elm.formType === "craftState"
    );
    console.log(
      "dynamicValidateForm.domains[findIndex]  ",
      dynamicValidateForm.domains[findIndex]
    );
    if (
      findIndex !== -1 &&
      !dynamicValidateForm.domains[findIndex].value?.length
    ) {
      dynamicValidateForm.domains[findIndex].value = res.data.content.map(
        (elm: CraftContent) => {
          return {
            ...elm,
            isDone: 0,
            isInputNum: elm.isInputNum !== undefined ? elm.isInputNum : 0,
          };
        }
      );
    }
    console.log("默认工艺获取完成了  ", res);
    setOrderStatus();
  }
};

// 打开工艺选择弹窗
const showCraftStateDialog = (index: number, val: CraftItem | null) => {
  if (!selectCraftStateDialogRef.value) return;
  activeCraftStateDomainIndex.value = index;
  selectCraftStateDialogRef.value.handleOpen(val);
};
// 弹窗确认
const craftStateSuccess = (data: CraftItem | null) => {
  if (data) {
    if (activeCraftStateDomainIndex.value > -1) {
      dynamicValidateForm.domains[activeCraftStateDomainIndex.value].value =
        data.content.map((elm) => {
          return {
            ...elm,
            isDone: 0, // 是否完成
            content: elm.content,
            isInputNum: elm.isInputNum !== undefined ? elm.isInputNum : 0,
          };
        });
    }
  }
  setOrderStatus();
};
// 修改工艺步骤逻辑

// 打开切换工艺状态弹窗
const showToggleCraftStateDialog = (
  item: CraftContent,
  index: number,
  craftList: CraftContent[]
) => {
  activeCraftList.value = craftList;
  editCraftStateDialogRef.value?.handleOpen({
    item: {
      ...item,
    },
    index,
    defaultReportingNum: defaultReportingNum.value,
  });
};

// 修改工艺步骤确认
const EditCraftStateSuccess = (data: { item: CraftContent; index: number }) => {
  if (!activeCraftList.value.length) {
    ElMessage({
      type: "error",
      message: "工艺修改错误请重试",
    });
    return;
  }
  Object.assign(activeCraftList.value[data.index], data.item);
  setOrderStatus();
  console.log("修改之后的值  ", activeCraftList.value[data.index]);
};

// 设置工单状态
const setOrderStatus = () => {
  // 工单查询出来的工艺列表
  const craftItem =
    dynamicValidateForm.domains.find((elm) => elm.key === "craft_state")
      ?.value || null;
  console.log("设置了工单状态   ", craftItem);
  // 查询出来的工单状态对象
  const orderStateItem =
    dynamicValidateForm.domains.find((elm) => elm.key === "order_state") ||
    null;
  if (!orderStateItem) {
    // 说明没有找到工单状态字段  无需设置
    return;
  }
  if (!craftItem || !craftItem.content || !craftItem.content.length) {
    // 没有工艺列表  直接设置未生产
    orderStateItem.value = 1;
    return;
  }
  if (
    craftItem.content.every(
      (elm: CraftContent) => Number(elm.isDone) === 0 || !Number(elm.isDone)
    )
  ) {
    // 最少有一个步骤没有完成
    orderStateItem.value = 1;
  } else if (
    craftItem.content.every((elm: CraftContent) => Number(elm.isDone) === 1)
  ) {
    // 全部完成啦
    orderStateItem.value = 3;
  } else {
    // 进行中
    orderStateItem.value = 2;
  }
};

// 设置剩余天数
watchEffect(() => {
  // 获取接车时间对象
  let carTimeObjIndex =
    dynamicValidateForm.domains.findIndex(
      (elm: OrderFieldItem) => elm.key === "116"
    ) || -1;
  // 获取剩余天数对象
  let dayObjIndex =
    dynamicValidateForm.domains.findIndex(
      (elm: OrderFieldItem) => elm.key === "day"
    ) || -1;
  if (carTimeObjIndex === -1 && dayObjIndex === -1) {
    return;
  }
  if (carTimeObjIndex === -1 && dayObjIndex !== -1) {
    dynamicValidateForm.domains[dayObjIndex].value = 0;
    return;
  }
  let diff = getDaysDifference(
    dynamicValidateForm.domains[carTimeObjIndex].value,
    formatTime(new Date())
  );
  dynamicValidateForm.domains[dayObjIndex].value = diff > 0 ? diff : 0;
  console.log(
    "剩余天数重新赋值了   ",
    dynamicValidateForm.domains[dayObjIndex].value
  );
});

// 提交工单

// 把下划线key转换成小驼峰key
const convertToCamelCase = (obj: { [key: string]: any }): object => {
  if (typeof obj !== "object" || obj === null) {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(convertToCamelCase);
  }
  return Object.keys(obj).reduce((acc: any, key) => {
    const camelCaseKey: string = key.replace(/_([a-z])/g, (match, p1) =>
      p1.toUpperCase()
    );
    acc[camelCaseKey] = convertToCamelCase(obj[key]);
    return acc;
  }, {});
};
// 最后提交函数
const handleSubmitOrder = async (isBack: boolean = false) => {
  let data: { [key: string]: any } = {};
  if (orderId.value) {
    // 先把工单详情返回的所有数据合并过去
    Object.assign(data, orderInfoDetail.value);
  }
  let extra = dynamicValidateForm.domains.map((elm) => {
    elm.value = elm.formType === "image" ? elm.value.join(",") : elm.value;
    data[elm.key] = elm.value;
    return elm;
  });
  if (!data.extra) {
    data.extra = extra;
  } else {
    data.extra = data.extra.map((elm: OrderFieldItem) => {
      const findObj =
        extra.find((cElm: OrderFieldItem) => cElm.key === elm.key) || null;
      if (findObj) {
        return {
          ...elm,
          ...findObj,
        };
      }
      return elm;
    });
  }

  data = convertToCamelCase(data);

  console.log("提交参数哇哦  ", data);
  let res = orderId.value
    ? await editOrder(orderId.value, data)
    : await addOrder(data);
  if (res) {
    console.log("提交成功了  ", res);
    let message = "新增成功";
    if (orderId.value) message = "修改成功";
    ElMessage({
      type: "success",
      message: message,
    });
    if (isBack) {
      handleBack();
    } else {
      resetForm(formRef.value);
    }
  }
};
// 返回
const handleBack = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
$formValueWidth: 220px;
.app-container {
  width: 100%;
  height: 100%;
  .ma-b-15 {
    margin-bottom: 15px;
  }
  .success__text {
    color: var(--el-color-success);
  }
  .primary__text {
    color: var(--el-color-primary);
  }
  .danger__text {
    color: var(--el-color-danger);
  }
  .app__form__container {
    padding: 10px 10px 70px 10px;

    .form__row__container {
      width: $formValueWidth;
    }
    .form__row__2__container {
      // width: 440px;
    }
    :deep(.el-date-editor) {
      width: $formValueWidth;
    }
    :deep(.el-select) {
      width: $formValueWidth;
    }
    .row_content-container {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .content_item-container {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        .item_content {
          flex-shrink: 0;
          padding: 3px 20px;
          border: 1px solid var(--el-border-color);
          cursor: pointer;
          &__success {
            color: var(--el-color-success);
            border: 1px solid var(--el-color-success);
            cursor: pointer;
          }
        }
        .step-text {
          flex: 1 1 auto;
          margin: 0 5px;
          display: flex;
          align-items: center;
          .icon {
            margin-left: 5px;
          }
        }
      }
    }
  }
  .app__bottom__container {
    padding: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color);
  }
}
</style>
